package me.zhengjie.modules.workorder.service.impl;

import com.fasterxml.jackson.annotation.JsonFormat;
import me.zhengjie.modules.customer.domain.TCustomerInfo;
import me.zhengjie.modules.customer.repository.TCustomerInfoRepository;
import me.zhengjie.modules.inspection.repository.TInspectionTaskRepository;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderInfo;
import me.zhengjie.modules.serviceprovider.repository.TServiceproviderInfoRepository;
import me.zhengjie.modules.system.common.EnumWorkorderStatus;
import me.zhengjie.modules.workorder.domain.TAccident;
import me.zhengjie.modules.workorder.domain.TTasks;
import me.zhengjie.modules.workorder.domain.TWorkOrder;
import me.zhengjie.modules.workorder.domain.TWorkOrderLog;
import me.zhengjie.modules.workorder.service.dto.TWorkOrderQueryCriteriaEx;
import me.zhengjie.utils.*;
import me.zhengjie.modules.workorder.repository.TAccidentRepository;
import me.zhengjie.modules.workorder.repository.TTasksRepository;
import me.zhengjie.modules.workorder.repository.TWorkOrderLogRepository;
import me.zhengjie.modules.workorder.repository.TWorkOrderRepository;
import me.zhengjie.modules.workorder.service.TWorkOrderService;
import me.zhengjie.modules.workorder.service.dto.TWorkOrderDTO;
import me.zhengjie.modules.workorder.service.dto.TWorkOrderQueryCriteria;
import me.zhengjie.modules.workorder.service.mapper.TWorkOrderMapper;
import org.hibernate.internal.CriteriaImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.persistence.Column;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
* @author zcw
* @date 2019-08-13
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TWorkOrderServiceImpl implements TWorkOrderService {

    @Autowired
    private TWorkOrderRepository tWorkOrderRepository;
    
    @Autowired
    private TTasksRepository tTasksRepository;
    
    @Autowired
    private TAccidentRepository tAccidentRepository;

    @Autowired
    private TWorkOrderMapper tWorkOrderMapper;
    
    @Autowired
    private TWorkOrderLogRepository tWorkOrderLogRepository;
    
    @Autowired
    private TInspectionTaskRepository tInspectionTaskRepository;

	@Autowired
	private TServiceproviderInfoRepository tServiceproviderInfoRepository;

	@Autowired
	private TCustomerInfoRepository tCustomerInfoRepository;

    @SuppressWarnings("unchecked")
	@Override
    public Object queryAll(TWorkOrderQueryCriteria criteria, Pageable pageable){
        Page<TWorkOrder> page = tWorkOrderRepository.findAll(getPredicate(criteria),pageable);
        Page<TWorkOrderDTO> pageDto = page.map(tWorkOrderMapper::toDto);
        List<TWorkOrderDTO> dtos = pageDto.getContent();
        if(CollectionUtil.isNotEmpty(dtos)) {
        	for(TWorkOrderDTO dto:dtos) {
        		if(dto.getOrderSource()==1) {
        			dto.setTaccident(tAccidentRepository.getOne(Long.valueOf(dto.getSourceId())));
        		} else if(dto.getOrderSource()==2) {
        			dto.setTask(tTasksRepository.getOne(dto.getSourceId()));
        		}else if(dto.getOrderSource()==3) {
        			dto.setInspection(tInspectionTaskRepository.getOne(Long.valueOf(dto.getSourceId())));
        		}
        	}
        }
        return PageUtil.toPage(pageDto);
    }

    private Specification getPredicate(TWorkOrderQueryCriteria criteria) {
		Specification specification = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				//增加筛选条件
				Predicate predicate = QueryHelp.getPredicate(root, criteria, cb);
				if(!StringUtils.isEmpty(criteria.getFinishTimeBegin())) {
					predicate.getExpressions().add(cb.greaterThanOrEqualTo(root.get("finishTime").as(String.class), criteria.getFinishTimeBegin()));
				}
				if(!StringUtils.isEmpty(criteria.getFinishTimeEnd())) {
					predicate.getExpressions().add(cb.lessThanOrEqualTo(root.get("finishTime").as(String.class), criteria.getFinishTimeBegin()));
				}
				Integer statusEx = criteria.getStatusEx();
				if(statusEx != null) {
					if(statusEx == EnumWorkorderStatus.CLOSED.getValue()) { //已结算未结算
						predicate.getExpressions().add(cb.equal(root.get("status").as(Integer.class), statusEx));
					} else {
						predicate.getExpressions().add(cb.notEqual(root.get("status").as(Integer.class), statusEx));
					}
				}
				return predicate;
			}
		};
		return specification;
	}

    @SuppressWarnings("unchecked")
	@Override
    public Object queryAll(TWorkOrderQueryCriteria criteria){
        return tWorkOrderMapper.toDto(tWorkOrderRepository.findAll(getPredicate(criteria)));
    }

	@Override
	public Object queryAll(TWorkOrderQueryCriteriaEx criteria, Pageable pageable) {
		Page<TWorkOrder> page = tWorkOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
		Page<TWorkOrderDTO> pageDto = page.map(tWorkOrderMapper::toDto);
		List<TWorkOrderDTO> dtos = pageDto.getContent();
		if(CollectionUtil.isNotEmpty(dtos)) {
			for(TWorkOrderDTO dto:dtos) {
				if(dto.getOrderSource()==1) {
					dto.setTaccident(tAccidentRepository.getOne(Long.valueOf(dto.getSourceId())));
				} else if(dto.getOrderSource()==2) {
					dto.setTask(tTasksRepository.getOne(dto.getSourceId()));
				}else if(dto.getOrderSource()==3) {
					dto.setInspection(tInspectionTaskRepository.getOne(Long.valueOf(dto.getSourceId())));
				}
			}
		}
		return PageUtil.toPage(pageDto);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Object queryAcceptableWorkOrder(String major, ArrayList<String> level, String country, String province,
										   String city, String county, Long supplier,Pageable pageable) {
		Page<TWorkOrder> page = tWorkOrderRepository.queryAcceptableWorkorder(major,level,country,province,city,county,supplier,pageable);
		Page<TWorkOrderDTO> pageDto = page.map(tWorkOrderMapper::toDto);
		List<TWorkOrderDTO> dtos = pageDto.getContent();
		if(CollectionUtil.isNotEmpty(dtos)) {
			for(TWorkOrderDTO dto:dtos) {
				if(dto.getOrderSource()==1) {
					dto.setTaccident(tAccidentRepository.getOne(Long.valueOf(dto.getSourceId())));
				} else if(dto.getOrderSource()==2) {
					dto.setTask(tTasksRepository.getOne(dto.getSourceId()));
				}else if(dto.getOrderSource()==3) {
					dto.setInspection(tInspectionTaskRepository.getOne(Long.valueOf(dto.getSourceId())));
				}
			}
		}
		return PageUtil.toPage(pageDto);
	}

	@Override
	public Long countAcceptableWorkOrder(String major, ArrayList<String> level, String country, String province, String city, String county, Long supplier) {
		return tWorkOrderRepository.countAcceptableWorkorder(major,level,country,province,city,county,supplier);
	}

	@Override
    public TWorkOrderDTO findById(Long id) {
        Optional<TWorkOrder> tWorkOrder = tWorkOrderRepository.findById(id);
        ValidationUtil.isNull(tWorkOrder,"TWorkOrder","id",id);
        return tWorkOrderMapper.toDto(tWorkOrder.get());
    }

	@Override
	public void create(List<TWorkOrder> workOrderList) {
		int index = 1;
		Long count = tWorkOrderRepository.count();

		for(TWorkOrder resources: workOrderList) {
			Integer orderSource = resources.getOrderSource();
			if (resources.getCustomerId() != null && StringUtils.isEmpty(resources.getCustomerName())) {
				Optional<TCustomerInfo> customerInfo = tCustomerInfoRepository.findById(resources.getCustomerId());
				if (customerInfo.isPresent()) {
					resources.setCustomerName(customerInfo.get().getCustomerName());  //客户名字
				}
			}
			resources.setStatus(EnumWorkorderStatus.CREATED.getValue()); //新建

			String id = String.valueOf(count);
			if (id.length() == 1) {
				id = "000" + id;
			} else if (id.length() == 2) {
				id = "00" + id;
			} else if (id.length() == 3) {
				id = "0" + id;
			}
			//***-(*)格式
			if(workOrderList.size() >= 1)
				id = String.format("%s-(%d)",id,index++);

			if (orderSource != null && orderSource == 1) {
				resources.setOrderCode("GZGD-" + DateUtil.format(new Date(), "YYYYMMdd") + id);
			} else if (orderSource != null && orderSource == 2) {
				resources.setOrderCode("RWGD-" + DateUtil.format(new Date(), "YYYYMMdd") + id);
			} else if (orderSource != null && orderSource == 3) {
				resources.setOrderCode("XJGD-" + DateUtil.format(new Date(), "YYYYMMdd") + id);
			} else {
				resources.setOrderCode(IdUtil.simpleUUID());
			}
			tWorkOrderRepository.save(resources);

			TWorkOrderLog log = new TWorkOrderLog();
			log.setOrderStatus(resources.getStatus());
			log.setOrderId(resources.getOrderCode());
			log.setOperator(SecurityUtils.getName());
			log.setCreateTime(new Timestamp(System.currentTimeMillis()));
			log.setContent("创建工单");
			tWorkOrderLogRepository.save(log);
		}
	}

	@Override
    @Transactional(rollbackFor = Exception.class)
    public TWorkOrderDTO create(TWorkOrder resources) {
    	Integer orderSource = resources.getOrderSource();

		if(resources.getCustomerId() != null) {
			Optional<TCustomerInfo> customerInfo = tCustomerInfoRepository.findById(resources.getCustomerId());
			if (customerInfo.isPresent()) {
				resources.setCustomerName(customerInfo.get().getCustomerName());  //客户名字
			}
		}
		resources.setStatus(EnumWorkorderStatus.CREATED.getValue()); //新建

		Long  count = tWorkOrderRepository.count() ;
    	//resources = tWorkOrderRepository.save(resources);

    	String id = String.valueOf(count);
    	if(id.length()==1) {
    		id="000"+id;
    	} else if(id.length()==2) {
    		id="00"+id;
    	} else if(id.length()==3) {
    		id="0"+id;
    	} 
    	if(orderSource!=null && orderSource==1) {
    		resources.setOrderCode("GZGD-"+DateUtil.format(new Date(), "YYYYMMdd")+id);
    	} else if (orderSource!=null && orderSource==2) {
    		resources.setOrderCode("RWGD-"+DateUtil.format(new Date(), "YYYYMMdd")+id);
    	} else if (orderSource!=null && orderSource==3) {
    		resources.setOrderCode("XJGD-"+DateUtil.format(new Date(), "YYYYMMdd")+id);
    	} else {
    		resources.setOrderCode(IdUtil.simpleUUID());
    	}
    	tWorkOrderRepository.save(resources);
    	
    	TWorkOrderLog log = new TWorkOrderLog();
    	log.setOrderStatus(resources.getStatus());
    	log.setOrderId(resources.getOrderCode());
    	log.setOperator(SecurityUtils.getName());
    	log.setCreateTime(new Timestamp(System.currentTimeMillis()));
    	log.setContent("创建工单");
    	tWorkOrderLogRepository.save(log);
    	
    	TWorkOrderDTO dto = tWorkOrderMapper.toDto(resources);
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBeforeAssign(TWorkOrder resources) {
        Optional<TWorkOrder> optionalTWorkOrder = tWorkOrderRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTWorkOrder,"TWorkOrder","id",resources.getId());

        TWorkOrder tWorkOrder = optionalTWorkOrder.get();
		//工单?不修改,工单来源
		tWorkOrder.setStatus(resources.getStatus()); //状态
		tWorkOrder.setServiceLevel(resources.getServiceLevel()); //等级, 没有使用
		tWorkOrder.setContractId(resources.getContractId()); //绑定合同,没有使用,根据供应商的对应的合同进行处理.
		tWorkOrder.setFaultType(resources.getFaultType()); // 故障类型
		// 服务商,派单后才有 supplier_id/supplier_name
		// 客户标识
		tWorkOrder.setCustomerId(resources.getCustomerId());
		tWorkOrder.setCustomerName(resources.getCustomerName());

		// 预约上门时间
		tWorkOrder.setAddriveTime(resources.getAddriveTime());
		// 预计服务时间
		tWorkOrder.setServiceTime(resources.getServiceTime()); //预估服务时间
		// 所需工具
		tWorkOrder.setRequireTool(resources.getRequireTool());
		// 备注
		tWorkOrder.setNotes(resources.getNotes());
        tWorkOrderRepository.save(tWorkOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
    	TWorkOrder order = tWorkOrderRepository.getOne(id);
    	if(order.getOrderSource()==1) {
			tAccidentRepository.deleteById(order.getSourceId());
		} else if(order.getOrderSource()==2) {
			tTasksRepository.deleteById(order.getSourceId());
		}else if(order.getOrderSource()==3) {
			tInspectionTaskRepository.deleteById(order.getSourceId());
		}
        tWorkOrderRepository.deleteById(id);
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void batchAssign(TWorkOrder resources) {
		String[] ids = resources.getEvaluater().split(",");  // 字段复用
		for(String id: ids) {
			resources.setId(Long.valueOf(id));

			Optional<TWorkOrder> optionalTWorkOrder = tWorkOrderRepository.findById(resources.getId());
			ValidationUtil.isNull( optionalTWorkOrder,"TWorkOrder","id",resources.getId());
			TWorkOrder tWorkOrder = optionalTWorkOrder.get();
			//tWorkOrder.setAssignOperator(resources.getAssignOperator());
			tWorkOrder.setAddriveTime(resources.getAddriveTime());
			tWorkOrder.setServiceLevel(resources.getServiceLevel());
			tWorkOrder.setFaultType(resources.getFaultType());
			tWorkOrder.setServiceTime(resources.getServiceTime());
			tWorkOrder.setSupplier(resources.getSupplier());
			tWorkOrder.setStatus(resources.getStatus());
			tWorkOrder.setContractId(resources.getContractId());  //合同
			tWorkOrder.setRequireTool(resources.getRequireTool());
			tWorkOrder.setNotes(resources.getNotes());
			tWorkOrder.setStatus(EnumWorkorderStatus.DISPATCHED.getValue()); //分派
			tWorkOrder.setAssignOperator(resources.getAssignOperator());
			tWorkOrder.setAssignTime(resources.getAssignTime());
			tWorkOrder.setMajor(resources.getMajor());
			tWorkOrder.setLevel(resources.getLevel());
			tWorkOrder.setFilterOption(resources.getFilterOption());

			Optional<TServiceproviderInfo> serviceproviderInfo = tServiceproviderInfoRepository.findById(resources.getSupplier());
			if(serviceproviderInfo.isPresent()) {
				tWorkOrder.setSupplierName(serviceproviderInfo.get().getSeproName());  //供应商名称
			}

			switch(tWorkOrder.getOrderSource()) {
				case 1: //故障单
					Optional<TAccident> optionalTAccident = tAccidentRepository.findById(tWorkOrder.getSourceId());
					TAccident accident = optionalTAccident.get();
					if(accident != null) {
						accident.setState(tWorkOrder.getStatus());
						tAccidentRepository.save(accident);  //修改状态

						tWorkOrder.setCountry(accident.getCountry());
						tWorkOrder.setProvince(accident.getProvince());
						tWorkOrder.setCity(accident.getCity());
						tWorkOrder.setCounty(accident.getCounty());
					}
					break;
				case 2: //任务单
					Optional<TTasks> optionalTask = tTasksRepository.findById(tWorkOrder.getSourceId());
					TTasks task = optionalTask.get();
					if(task != null) {
						task.setState(tWorkOrder.getStatus());
						tTasksRepository.save(task);  //派单状态

						tWorkOrder.setCountry(task.getCountry());
						tWorkOrder.setProvince(task.getProvince());
						tWorkOrder.setCity(task.getCity());
						tWorkOrder.setCounty(task.getCounty());
					}
					break;
				case 3:
					//TODO@@@@@00001 巡检计划处理
					break;
				default:

					break;
			}

			//修改工单信息,含专业\等级\地域等信息
			tWorkOrderRepository.save(tWorkOrder);

			TWorkOrderLog log = new TWorkOrderLog();
			log.setOrderStatus(tWorkOrder.getStatus());
			log.setOrderId(tWorkOrder.getOrderCode());
			log.setOperator(SecurityUtils.getName());
			log.setCreateTime(new Timestamp(System.currentTimeMillis()));
			String content = "平台批量派单";
			if(tWorkOrder.getStatus() == EnumWorkorderStatus.DENY.getValue() ||
					tWorkOrder.getStatus() == EnumWorkorderStatus.BACK.getValue()) { //
				content = "平台重新批量派单";
			}
			log.setContent(content);
			tWorkOrderLogRepository.save(log);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void assign(TWorkOrder resources) {
		Optional<TWorkOrder> optionalTWorkOrder = tWorkOrderRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTWorkOrder,"TWorkOrder","id",resources.getId());
        TWorkOrder tWorkOrder = optionalTWorkOrder.get();
        //tWorkOrder.setAssignOperator(resources.getAssignOperator());
        tWorkOrder.setAddriveTime(resources.getAddriveTime());
        tWorkOrder.setServiceLevel(resources.getServiceLevel());
        tWorkOrder.setFaultType(resources.getFaultType());
        tWorkOrder.setServiceTime(resources.getServiceTime());
        tWorkOrder.setSupplier(resources.getSupplier());
        tWorkOrder.setStatus(resources.getStatus());
		tWorkOrder.setContractId(resources.getContractId());  //合同
		tWorkOrder.setRequireTool(resources.getRequireTool());
		tWorkOrder.setNotes(resources.getNotes());
        tWorkOrder.setStatus(EnumWorkorderStatus.DISPATCHED.getValue()); //分派
		tWorkOrder.setAssignOperator(resources.getAssignOperator());
		tWorkOrder.setAssignTime(resources.getAssignTime());
		tWorkOrder.setMajor(resources.getMajor());
		tWorkOrder.setLevel(resources.getLevel());
		tWorkOrder.setFilterOption(resources.getFilterOption());

		Optional<TServiceproviderInfo> serviceproviderInfo = tServiceproviderInfoRepository.findById(resources.getSupplier());
		if(serviceproviderInfo.get() != null) {
			tWorkOrder.setSupplierName(serviceproviderInfo.get().getSeproName());  //供应商名称
		}


		switch(tWorkOrder.getOrderSource()) {
			case 1: //故障单
				Optional<TAccident> optionalTAccident = tAccidentRepository.findById(tWorkOrder.getSourceId());
				TAccident accident = optionalTAccident.get();
				if(accident != null) {
					accident.setState(tWorkOrder.getStatus());
					tAccidentRepository.save(accident);  //修改状态

					tWorkOrder.setCountry(accident.getCountry());
					tWorkOrder.setProvince(accident.getProvince());
					tWorkOrder.setCity(accident.getCity());
					tWorkOrder.setCounty(accident.getCounty());
				}
				break;
			case 2: //任务单
				Optional<TTasks> optionalTask = tTasksRepository.findById(tWorkOrder.getSourceId());
				TTasks task = optionalTask.get();
				if(task != null) {
					task.setState(tWorkOrder.getStatus());
					tTasksRepository.save(task);  //派单状态

					tWorkOrder.setCountry(task.getCountry());
					tWorkOrder.setProvince(task.getProvince());
					tWorkOrder.setCity(task.getCity());
					tWorkOrder.setCounty(task.getCounty());
				}
				break;
			case 3:
				//TODO@@@@@00001 巡检计划处理
				break;
			default:

				break;
		}

		//修改工单信息,含专业\等级\地域等信息
		tWorkOrderRepository.save(tWorkOrder);
        
        TWorkOrderLog log = new TWorkOrderLog();
    	log.setOrderStatus(tWorkOrder.getStatus());
    	log.setOrderId(tWorkOrder.getOrderCode());
    	log.setOperator(SecurityUtils.getName());
    	log.setCreateTime(new Timestamp(System.currentTimeMillis()));
		String content = "平台派单";
		if(tWorkOrder.getStatus() == EnumWorkorderStatus.DENY.getValue() ||
				tWorkOrder.getStatus() == EnumWorkorderStatus.BACK.getValue()) { //
			content = "平台重新派单";
		}
    	log.setContent(content);
    	tWorkOrderLogRepository.save(log);
        
	}

	@Override
	public void acceptEx(TWorkOrder resources) {
		Optional<TWorkOrder> optionalTWorkOrder = tWorkOrderRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTWorkOrder,"TWorkOrder","id",resources.getId());

        TWorkOrder tWorkOrder = optionalTWorkOrder.get();
        tWorkOrder.setAcceptOperator(SecurityUtils.getName());
        tWorkOrder.setAcceptTime(new Timestamp(System.currentTimeMillis()));
        tWorkOrder.setEngineer(resources.getEngineer());
        tWorkOrder.setStatus(resources.getStatus());
        resources.setStatus(EnumWorkorderStatus.ACCEPTED.getValue());
        tWorkOrderRepository.save(tWorkOrder);
        
        TWorkOrderLog log = new TWorkOrderLog();
    	log.setOrderStatus(tWorkOrder.getStatus());
    	log.setOrderId(tWorkOrder.getOrderCode());
    	log.setOperator(SecurityUtils.getName());
    	log.setCreateTime(new Timestamp(System.currentTimeMillis()));
    	log.setContent("服务商派单："+resources.getEngineer());
    	tWorkOrderLogRepository.save(log);
	}

	@Override
	public void refuse(TWorkOrder resources) {
		Optional<TWorkOrder> optionalTWorkOrder = tWorkOrderRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTWorkOrder,"TWorkOrder","id",resources.getId());

        TWorkOrder tWorkOrder = optionalTWorkOrder.get();
        tWorkOrder.setAcceptOperator(null);
        tWorkOrder.setAcceptTime(null);
        tWorkOrder.setEngineer(null);
        tWorkOrder.setSupplier(null);
        tWorkOrder.setStatus(resources.getStatus());
        tWorkOrderRepository.save(tWorkOrder);
        
        TWorkOrderLog log = new TWorkOrderLog();
    	log.setOrderStatus(tWorkOrder.getStatus());
    	log.setOrderId(tWorkOrder.getOrderCode());
    	log.setOperator(SecurityUtils.getUsername());
    	log.setCreateTime(new Timestamp(System.currentTimeMillis()));
    	log.setContent("服务商拒单");
    	tWorkOrderLogRepository.save(log);
	}

	@Override
	public void repair(Long id) {
		Optional<TWorkOrder> optionalTWorkOrder = tWorkOrderRepository.findById(id);
		TWorkOrder tWorkOrder = optionalTWorkOrder.get();
        tWorkOrder.setStatus(400);
        tWorkOrderRepository.save(tWorkOrder);
        
        TWorkOrderLog log = new TWorkOrderLog();
    	log.setOrderStatus(tWorkOrder.getStatus());
    	log.setOrderId(tWorkOrder.getOrderCode());
    	log.setOperator(SecurityUtils.getUsername());
    	log.setCreateTime(new Timestamp(System.currentTimeMillis()));
    	tWorkOrderLogRepository.save(log);
	}
	
	@Override
	public void reform(TWorkOrder resources) {
		Optional<TWorkOrder> optionalTWorkOrder = tWorkOrderRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTWorkOrder,"TWorkOrder","id",resources.getId());

        TWorkOrder tWorkOrder = optionalTWorkOrder.get();
        tWorkOrder.setEngineer(resources.getEngineer());
        tWorkOrder.setStatus(resources.getStatus());
        tWorkOrderRepository.save(tWorkOrder);
        
        TWorkOrderLog log = new TWorkOrderLog();
    	log.setOrderStatus(tWorkOrder.getStatus());
    	log.setOrderId(tWorkOrder.getOrderCode());
    	log.setOperator(SecurityUtils.getUsername());
    	log.setCreateTime(new Timestamp(System.currentTimeMillis()));
    	tWorkOrderLogRepository.save(log);
	}

	@Override
	public void check(Long id) {
		Optional<TWorkOrder> optionalTWorkOrder = tWorkOrderRepository.findById(id);
		TWorkOrder tWorkOrder = optionalTWorkOrder.get();
        tWorkOrder.setStatus(500);
        tWorkOrderRepository.save(tWorkOrder);
        
        TWorkOrderLog log = new TWorkOrderLog();
    	log.setOrderStatus(tWorkOrder.getStatus());
    	log.setOrderId(tWorkOrder.getOrderCode());
    	log.setOperator(SecurityUtils.getUsername());
    	log.setCreateTime(new Timestamp(System.currentTimeMillis()));
    	tWorkOrderLogRepository.save(log);
	}
	
	@Override
	public void back(Long id) {
		Optional<TWorkOrder> optionalTWorkOrder = tWorkOrderRepository.findById(id);
        TWorkOrder tWorkOrder = optionalTWorkOrder.get();
        tWorkOrder.setStatus(600);
        tWorkOrderRepository.save(tWorkOrder);
        
        TWorkOrderLog log = new TWorkOrderLog();
    	log.setOrderStatus(tWorkOrder.getStatus());
    	log.setOrderId(tWorkOrder.getOrderCode());
    	log.setOperator(SecurityUtils.getUsername());
    	log.setCreateTime(new Timestamp(System.currentTimeMillis()));
    	tWorkOrderLogRepository.save(log);
	}

    @Override
    public List<?> getWorkOrderAggByStatus(Long serviceproviderid, Long supplier) {
		if(serviceproviderid != null)
        	return tWorkOrderRepository.getWorkOrderAggByStatus(serviceproviderid,supplier);
		else
			return tWorkOrderRepository.getWorkOrderAggByStatus();
    }

	@Override
	public TWorkOrder findByOrderCode(String orderCode) {
		return tWorkOrderRepository.findFirstByOrderCode(orderCode);
	}

	@Override
	public Page<java.util.Map<?,?>> queryWorkorderReport(TWorkOrderQueryCriteriaEx criteria, Pageable pageable) {
		Page<java.util.Map<?,?>> results = tWorkOrderRepository.queryCustomerWorkorderReport(criteria.getOrderSource(),
				criteria.getEvaluateTimeBegin(),
				criteria.getEvaluateTimeEnd(),
				criteria.getCustomerName(),
				criteria.getSupplierName(),
				criteria.getOrderCode(),
				pageable);
		return results;
	}

	@Override
	public List<java.util.Map<?,?>> queryWorkorderReport(TWorkOrderQueryCriteriaEx criteria) {
		return tWorkOrderRepository.queryCustomerWorkorderReport(criteria.getOrderSource(),
				criteria.getEvaluateTimeBegin(),
				criteria.getEvaluateTimeEnd(),
				criteria.getCustomerName(),
				criteria.getSupplierName(),
				criteria.getOrderCode());
	}
}